package com.fc.remoting.core;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.fc.commons.JsonUtils;
import com.fc.remoting.logger.LogSystem;
import com.fc.remoting.logger.MonitorConfig;
import com.fc.remoting.logger.Monitorlogger;
import com.fc.remoting.logger.RemotingLogger;
import com.fc.remoting.protocol.IProtocol;
import com.fc.remoting.protocol.RemotingHttpProtocol;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;

public class HttpProtocolTask implements Runnable,Serializable {
	
	Logger log = LoggerFactory.getLogger(HttpProtocolTask.class);
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JSONObject request = null;
	private RemotingHttpProtocol handler = null;
	private ChannelHandlerContext ctx;

	public HttpProtocolTask(ChannelHandlerContext ctx, IProtocol handler, JSONObject request) {
		this.ctx = ctx;
		this.handler = (RemotingHttpProtocol) handler;
		this.request = request;
	}

	@Override
	public void run() {
		RemotingLogger.getLogger().info(request.toJSONString());
	
		Object msg = null;
		try {
			LogSystem.instance().protocolProcessBegin(log,ctx.channel(), request);
			msg = handler.doHandler(null,request);/*handler.doHandler(ctx.channel(),request);*/
			//返回客户端信
			if(msg != null){
				FullHttpResponse response = null;
				
				try {
					response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
							HttpResponseStatus.OK, Unpooled.wrappedBuffer(JsonUtils.object2String(msg).getBytes("UTF-8")));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
		        response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
		        response.headers().set(HttpHeaders.Names.CONTENT_LENGTH,
		                response.content().readableBytes());
		                
				ctx.write(response);
				ctx.flush();
			}
			LogSystem.instance().protocolProcessComplete(log,ctx.channel(),msg,null);
//			if(msg==null || !((JSONObject)msg).get("code").equals("1")){
//				Monitorlogger.monitorLog(MonitorConfig.app, MonitorConfig.handleModule, MonitorConfig.fail,null,request,msg);
//			}
		} catch (Exception e1) {
			LogSystem.instance().protocolProcessComplete(log,ctx.channel(),msg,e1);
		}
		
	}
}